// pages/login/index.js
Page({
  data: {
    inviteCode: "",
    getPhonePop: false,
    userInfo: {},
    checked: false
  },
  onLoad: function (options) {
    // const eventChannel = this.getOpenerEventChannel();
    // eventChannel.on("token_expire", function () {
    //   getApp().globalData.vant.toast("登录已过期");
    // });
    console.log(options.scene)
    if (!!options.scene) {
      this.setData({
        inviteCode: decodeURIComponent(options.scene)
      })
    }
  },
  onChange(e) {
    this.setData({
      checked: e.detail,
    });
  },
  getUserProfile(e) {
    if (!this.data.checked) {
      getApp().globalData.vant.toast("请阅读并勾选同意相关协议");
    } else {
      wx.getUserProfile({
        desc: "用于完善会员资料", // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
        success: (res) => {
          this.setData({
            getPhonePop: true,
            userInfo: res.userInfo
          });
          wx.setStorageSync("userInfo", res.userInfo);
          getApp().globalData.userInfo = res.userInfo;
        }
      });
    }
  },
  getPhoneNumber(e) {
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      this.setData({
        getPhonePop: false,
      });
      getApp().globalData.vant.toast.loading({
        message: "登录中...",
        duration: 0
      });
      this.userLogin(() => {
        getApp().globalData.http.updateUserInfo({
          nickName: this.data.userInfo.nickName,
          gender: this.data.userInfo.gender,
          avatarUrl: this.data.userInfo.avatarUrl,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }).then(res => {
          wx.setStorageSync("firstLogin", true);
          getApp().globalData.vant.toast({
            type: "success",
            message: "登录成功",
            duration: 1000,
            onClose: () => {
              wx.switchTab({
                url: "/pages/home/home",
                success: function (e) {
                  var page = getCurrentPages().pop();
                  if (page == undefined || page == null) return;
                  page.onLoad();
                }
              });
            },
          });
        }).catch(e => {
          getApp().globalData.vant.toast.fail(e.msg);
          wx.login({
            success: res => {
              getApp().globalData.code = res.code;
            }
          });
        });
      })
    }
  },
  userLogin(callback) {
    getApp().globalData.http.login({
      code: getApp().globalData.code,
      inviteCode: this.data.inviteCode
    }).then(res => {
      //请求成功
      wx.setStorageSync("token", res.data.token);
      callback && callback();
    }).catch(e => {
      getApp().globalData.vant.toast.fail(e.msg);
      wx.login({
        success: res => {
          getApp().globalData.code = res.code;
        }
      });
    });
  }
})